<?php

namespace IDock\Insurance\DAJIA\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\DAJIA\DAJIAEnums;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumFactorPrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\Premium\PremiumTaxPrinter;
use IDock\Printer\SpecialClausesPrinter;
use IDock\Printer\VehiclePrinter;

class InsurancePriceQueryResponse extends AllDAJIAResponse
{
    public $jqRenewMrk = '';

    public $syRenewMrk = '';

    public $isNewEnergy = 0;

    public function printerInit(): Response
    {
        $premiumInquiryPrinter = new PremiumInquiryPrinter();

        $premiumInquiryPrinter->success = true;
        $data = $this->get('body', []);
        $basePart = $data['result']['basePart'] ?? [];
        $riskRatio = $data['result']['riskRatio'] ?? [];
        $jqStatus = $data['result']['jqAppStatus'];
        $error = [];
        $ciDesc = $data['result']['jqAppStatusMessage'] ?? '';
        $biDesc = $data['result']['reInsuredInfo'] ?? '';

        $this->getRepeatData($premiumInquiryPrinter, $ciDesc, $biDesc);

        if ($premiumInquiryPrinter->repeatInsuredFlg) {
            $premiumInquiryPrinter->success = false;
            $premiumInquiryPrinter->repeatMessage = $ciDesc . "\r\n" . $biDesc;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        if (empty($jqStatus) && $jqStatus !== null) {
            $error[] = "交强险询价异常:" . $data['result']['jqAppStatusMessage'] ?? '';
        }
        $syStatus = $data['result']['syAppStatus'];
        if (empty($syStatus) && $syStatus !== null) {
            $error[] = "商业险询价异常:" . $data['result']['syAppStatusMessage'] ?? '';
        }
        if (!empty($error)) {
            $this->setError(implode("\r\n", $error));
            $premiumInquiryPrinter->success = false;
            $this->printer = $premiumInquiryPrinter;
            return $this;
        }
        //交强险
        $premiumInquiryPrinter->inquiryNo = $basePart['jqProposalNo'] . $basePart['syProposalNo'];//总询价单号
        $premiumInquiryPrinter->ciInquiryNo = $basePart['jqProposalNo'];//交强险询价单号
        $ciPremiumPrinter = new PremiumCIPrinter();//商业险询价信息
        $ciPremiumPrinter->ciPremium = $basePart['jqPremium'] ?? '';//交强险保费
        $ciPremiumPrinter->ciStartData = $basePart['jqEffectiveDate'] ?? '';//交强险起保日期
        $ciPremiumPrinter->ciEndData = $basePart['jqExpireDate'] ?? '';//交强险终保日期
        $ciPremiumPrinter->ciBasePremium = $basePart['jqPremium'] ?? '0';//交强险保费（不含增值税）
        $ciPremiumPrinter->ciDiscount = $riskRatio['jqDisCount'] ?? '1';//交强折扣率
        $premiumInquiryPrinter->ciPremiumPrinter = $ciPremiumPrinter;

        $carTaxPrinter = new PremiumTaxPrinter();
        $carTaxPrinter->carShipTax = $data['result']['vehicleTaxation']['taxTotalAmount'] ?? 0;
        $carTaxPrinter->thisYearTax = $data['result']['vehicleTaxation']['taxableAmt'] ?? 0;//本年应缴税
        $carTaxPrinter->overdue = $data['result']['vehicleTaxation']['taxOverdueAmt'] ?? 0;
        $carTaxPrinter->payBackTax = $data['result']['vehicleTaxation']['taxLastYear'] ?? 0;
        $premiumInquiryPrinter->carTaxPrinter = $carTaxPrinter;


        $biPremiumPrinter = new PremiumBIPrinter();
        $premiumInquiryPrinter->biInquiryNo = $basePart['syProposalNo'] ?? '';//商业险询价单号
        $biPremiumPrinter->biPremium = $basePart['syPremium'] ?? '';//商业险保费
        $biPremiumPrinter->biStartData = $basePart['syEffectiveDate'] ?? '';//商业险起保日期
        $biPremiumPrinter->biEndData = $basePart['syExpireDate'] ?? '';//商业险终保日期
        $biPremiumPrinter->biBasePremium = 0;//商业险基础保费
        $biPremiumPrinter->biDiscount = $riskRatio['syDisCount'] ?? '';
        $premiumInquiryPrinter->biPremiumPrinter = $biPremiumPrinter;

        $coverageList = $data['result']['coverageList'] ?? [];
        $biBasePremium = 0;
        foreach ($coverageList as $row) {
            $coverage = new PremiumCoveragePrinter();
            $coverage->coverageCode = array_search($row['cvrgNo'], DAJIAEnums::$coverageCode);
            $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            $coverage->amount = $row['amt'] ?? 0;
            $coverage->premium = $row['premium'] ?? 0;
            $coverage->basePremium = $row['basicPremium'] ?? 0;
            $coverage->discount = $row['discountValue'] ?? 0;
            $biBasePremium += $row['basePremium'] ?? 0;
            $coverage->serviceTimes = $row['severTimes'] ?? '0';
            $premiumInquiryPrinter->coverageListAppend($coverage);
        }
        $biPremiumPrinter->biBasePremium = $biBasePremium;
        $modelList = $data['result']['carModelList'] ?? [];
        foreach ($modelList as $val) {
            $carModel = new VehiclePrinter();
            $carModel->vehicleName = $val['cCarName'] ?? '';
            $carModel->brandName = $val['cBrand'] ?? '';
            $carModel->familyName = $val['cSeries'] ?? '';
            $carModel->vehicleModelCode = $val['vehicleStyleUniqueId'] ?? '';
            $carModel->vehicleExhaust = $val['displacement'] ?? 0;
            $carModel->vehicleSeat = $val['limitLoadPerson'] ?? 0;
            $carModel->energyTypeCode = $val['modelEnergyType'] ?? '';
            $carModel->wholeWeight = $val['curbWt'] ?? '';
            $premiumInquiryPrinter->vehicleModelAppend($carModel);
        }
        //特约
        $engageList = [];
        if (!empty($data['result']['jqSpecialEngageList'])) foreach ($data['result']['jqSpecialEngageList'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['specialClausesCode'];
            $engage->clauseCode = $val['specialClausesCode'];
            $engage->clauseContent = $val['specialClausesContent'];
            $engage->autoFlag = '1';
            $engage->riskType = 'TCI';//交强险固定特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }
        if (!empty($data['result']['sySpecialEngageList'])) foreach ($data['result']['sySpecialEngageList'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['specialClausesCode'];
            $engage->clauseCode = $val['specialClausesCode'];
            $engage->clauseContent = $val['specialClausesContent'];
            $engage->autoFlag = '1';
            $engage->riskType = 'VCI';//商业险固定特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }
        if (!empty($data['result']['jqSpecialEngageAllList'])) foreach ($data['result']['jqSpecialEngageAllList'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['specialClausesCode'];
            $engage->clauseCode = $val['specialClausesCode'];
            $engage->clauseContent = $val['specialClausesContent'];
            $engage->autoFlag = '0';
            $engage->riskType = 'TCI';//交强险可选特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }
        if (!empty($data['result']['sySpecialEngageAllList'])) foreach ($data['result']['sySpecialEngageAllList'] as $val) {
            $engage = new SpecialClausesPrinter();
            $engage->clauseName = $val['specialClausesCode'];
            $engage->clauseCode = $val['specialClausesCode'];
            $engage->clauseContent = $val['specialClausesContent'];
            $engage->autoFlag = '0';
            $engage->riskType = 'VCI';//商业险可选特约
            $premiumInquiryPrinter->specialClausesAppend($engage);
        }
        //交商系数
        $premiumInquiryPrinter->ncdFactor = $riskRatio['syResvNum2'] ?? '';
        $factorPrinter = new PremiumFactorPrinter();
        $factorPrinter->TCIFactorAppend('交强险赔付率(%)', 'ciJqecompensationRate', $riskRatio['billCTPELR'] ?? '');
        $factorPrinter->TCIFactorAppend('饮酒一次费率浮动', 'cResvTxt1', $riskRatio['cResvTxt1'] ?? '');
        $factorPrinter->TCIFactorAppend('醉酒一次费率浮动', 'cResvTxt2', $riskRatio['cResvTxt2'] ?? '');
        $factorPrinter->TCIFactorAppend('饮酒后驾驶违法行为次数', 'nResvNum1', $riskRatio['nResvNum1'] ?? '');
        $factorPrinter->TCIFactorAppend('醉酒后驾驶违法行为次数', 'jqResvNum2', $riskRatio['jqResvNum2'] ?? '');
        $factorPrinter->TCIFactorAppend('交强大家分', 'pubScoresCI', $riskRatio['jqPubScores'] ?? '');
        $factorPrinter->TCIFactorAppend('交强上年出险次数', 'jqPreEscNum', $riskRatio['jqPreEscNum'] ?? '');
        $factorPrinter->TCIFactorAppend('交强险佣金比例', 'ciRpaCommissionRate', $basePart['jqCommissionRate'] ?? '');

        $factorPrinter->VCIFactorAppend('商业险赔付率(%)', 'biNecompensationRate', $riskRatio['billCOMELR'] ?? '');
        $factorPrinter->VCIFactorAppend('赔款优待及上年赔款浮动原因', 'cAgoClmRec', $riskRatio['cAgoClmRec'] ?? '');
        $factorPrinter->VCIFactorAppend('无赔优不浮动原因代码', 'cNoClaimRes', $riskRatio['cNoClaimRes'] ?? '');
        $factorPrinter->VCIFactorAppend('交通违法系数', 'nResvNum8', $riskRatio['nResvNum8'] ?? '');
        $factorPrinter->VCIFactorAppend('连续承保年数', 'cInsureYears', $riskRatio['cInsureYears'] ?? '');
        $factorPrinter->VCIFactorAppend('连续承保期间出险次数', 'cClaimTimes', $riskRatio['cClaimTimes'] ?? '');
        $factorPrinter->VCIFactorAppend('无赔优系数级别', 'cClaimAdjustLevel', $riskRatio['cClaimAdjustLevel'] ?? '');
        $factorPrinter->VCIFactorAppend('商业大家分', 'pubScoresBI', $riskRatio['syPubScores'] ?? '');
        $factorPrinter->VCIFactorAppend('商业上年出险次数', 'syPreEscNum', $riskRatio['syPreEscNum'] ?? '');
        $factorPrinter->VCIFactorAppend('商业险佣金比例', 'biRpaCommissionRate', $basePart['syCommissionRate'] ?? '');

        $factorPrinter->ComFactorAppend('期望折扣双系数', 'expDisc', $riskRatio['expDisc'] ?? '');
        $factorPrinter->ComFactorAppend('整单预期赔付率', 'billELR', $riskRatio['billELR'] ?? '');
        $factorPrinter->ComFactorAppend('自主定价系数', 'selfPricingCoef', $riskRatio['pricingAdjustValue'] ?? '');
        $factorPrinter->ComFactorAppend('家用车风险评分', 'zcrkScore', $riskRatio['zcrkScore'] ?? '');
        $this->jqRenewMrk = $basePart['jqRenewMrk'] ?? '';
        $this->syRenewMrk = $basePart['syRenewMrk'] ?? '';

        $premiumInquiryPrinter->premiumFactorPrinter = $factorPrinter;
        $this->printer = $premiumInquiryPrinter;
        return $this;
    }

    /**
     * 重复投保
     * @param PremiumInquiryPrinter $premiumInquiryPrinter
     * @param $ciMeg
     * @param $biMeg
     */
    public function getRepeatData(PremiumInquiryPrinter $premiumInquiryPrinter, $ciMeg, $biMeg)
    {
        if ($ciMeg and preg_match('/终保日期 ([\d\s:-]+)/', $ciMeg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $premiumInquiryPrinter->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $premiumInquiryPrinter->repeatInsuredFlg = true;
            }
        }

        if ($biMeg and preg_match('/终保日期：([\d]+)/', $biMeg, $matches2)) {
            if ($matches2[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches2[1]));

                $premiumInquiryPrinter->repeatInsurePrinter['biStartData'] = $biStartData;
                $premiumInquiryPrinter->repeatInsuredFlg = true;
            }
        }
    }

    /**
     * 转换为新能源险种
     * @param $isNewEnergy
     * @return void
     */
    public function translateCoverageCode($isNewEnergy)
    {
        if (!$isNewEnergy) return;
        /**
         * @var PremiumInquiryPrinter $printer
         */
        $printer = $this->printer;
        $coverageList = $printer->coverageList;
        /**
         * @var PremiumCoveragePrinter $value
         */
        foreach ($coverageList as &$value) {
            $value->coverageCode = "C1" . substr($value->coverageCode, 2, 4);
        }
    }
}
